package com.cskaoyan.app.config;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cskaoyan.app.bean.common.OSS;
import com.cskaoyan.app.bean.common.SMS;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

@Component
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliComponent {

    private String accessKeyId;
    private String accessKeySecret;
    private OSS oss;
    private SMS sms;

    public OSSClient getOssClient() {
        return new OSSClient(oss.getEndPoint(), accessKeyId, accessKeySecret);

    }

    public PutObjectResult fileUpload(String fileName, File file) {
        OSSClient ossClient = getOssClient();
        return ossClient.putObject(oss.getBucket(), fileName, file);
    }

    public PutObjectResult fileUpload(String fileName, InputStream inputStream) {
        OSSClient ossClient = getOssClient();
        return ossClient.putObject(oss.getBucket(), fileName, inputStream);
    }

    public String getUrl(String fileName) {
        return "https://" + oss.getBucket() + "." + oss.getEndPoint() + "/" + fileName;
    }

    public void sendMsg(String phoneNumber, String code){
        String signName = sms.getSignName();
        String templateCode = sms.getTemplateCode();

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        request.putQueryParameter("PhoneNumbers", phoneNumber);


        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            client.getCommonResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
